﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreEx.DynamicInvoker;
using CoreEx.MicroMapper;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;

namespace CoreEx.Database.Linq.Implementation
{
    [Implements(typeof(IMaterializer))]
    public class Materializer : IMaterializer, IInitialize
    {
        private IServiceContainer _serviceContainer;
        
        public void Materilize(ITranslateResult_old translateResult)
        {
            var genericMapper = typeof(ITableMapper<>).MakeGenericType(translateResult.ProjectedType);
            var mapper = _serviceContainer.GetService(genericMapper);
            var applyMethod =
              mapper.GetType().GetMethods().Where(
                  m => m.GetParameters().Any(p => typeof(IEnumerable).IsAssignableFrom(p.ParameterType))).FirstOrDefault();
            translateResult.Result = (IList)applyMethod.DynamicInvoke(mapper, new object[] { translateResult.Table });

            foreach (var memberResult in translateResult.MemberResults.Values)
            {
                Materilize(memberResult);
            }

        }


        public void Initialize(IServiceContainer source)
        {
            _serviceContainer = source;
        }
    }
}
